package com.company;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author 1reedom
 * @Create 2020/9/21 20:08
 */
public class ReflectServiceImpl {
    public void sayHello(String name){
        System.out.println("Hello"+name);
    }
    public ReflectServiceImpl getInstance(){
        ReflectServiceImpl object = null;
        try {
            object = (ReflectServiceImpl)Class.forName("com.work.ReflectServiceImpl").newInstance();
        }catch (ClassNotFoundException | InstantiationException
        | IllegalAccessException ex){
            ex.printStackTrace();
        }
        return object;
    }

    public Object reflectMethod(){
        Object returnObj = null ;
        ReflectServiceImpl target = new ReflectServiceImpl();
        try {
            Method method = ReflectServiceImpl.class.getMethod("sayHello",String.class);
            returnObj = method.invoke(target,"张三");
        }catch (NoSuchMethodException | SecurityException
                | IllegalAccessException
                | IllegalArgumentException
                | InvocationTargetException ex){
            ex.printStackTrace();
        }
        return returnObj;
    }

    public Object reflect(){
        ReflectServiceImpl object = null ;
        try {
            object = (ReflectServiceImpl)Class.forName("com.work.ReflectServiceImpl").newInstance();
            Method method = object.getClass().getMethod("sayHello", String.class);
            method.invoke(object,"张三");
        }catch (NoSuchMethodException | SecurityException|ClassNotFoundException
                | IllegalAccessException
                | IllegalArgumentException
                | InvocationTargetException
                |InstantiationException ex){
            ex.printStackTrace();
        }
        return object;
    }
}
